package com.cema.manage.project.android.biz;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.cema.manage.common.exception.BizException;
import com.cema.manage.common.exception.RiskException;
import com.cema.manage.common.utils.DateUtils;
import com.cema.manage.common.utils.IpUtils;
import com.cema.manage.project.android.TestBaseContrller;
import com.cema.manage.project.android.model.LoginVo;
import com.cema.manage.project.android.model.PageVo;
import com.cema.manage.project.android.model.UserDailyActivityVo;
import com.cema.manage.project.android.model.result.BizRankingList;
import com.cema.manage.project.android.result.JsonResult;
import com.cema.manage.project.android.service.BizAntiCheatService;
import com.cema.manage.project.android.service.BizUserService;
import com.cema.manage.project.enums.RedisEnum;
import com.cema.manage.project.enums.RiskEnum;
import com.cema.manage.project.manage.antiCheat.service.IAntiCheatService;
import com.cema.manage.project.manage.antiCheatDetail.domain.AntiCheatDetail;
import com.cema.manage.project.manage.userDailyActivity.service.IUserDailyActivityService;
import com.cema.manage.project.manage.users.domain.Users;
import com.cema.manage.project.manage.users.domain.UsersInfoVo;
import com.cema.manage.project.manage.usersLogout.domain.UsersLogout;
import com.cema.manage.project.manage.usersLogout.service.IUsersLogoutService;
import com.cema.manage.redis.RedisService;
import org.apache.ibatis.annotations.Mapper;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

@RestController
@RequestMapping("user")
public class BizUserController extends TestBaseContrller {
    @Resource
    private BizUserService bizUserService;

    @Resource
    private RedisService redisService;

    @Resource
    private BizAntiCheatService bizAntiCheatService;

    @Resource
    private IAntiCheatService iAntiCheatService;

    @Resource
    private IUserDailyActivityService iUserDailyActivityService;

    @Resource
    private IUsersLogoutService iUsersLogoutService;

    private final ReentrantLock lock = new ReentrantLock();

    @PostMapping("registerOrLogin")
    public JsonResult login(LoginVo loginVo, HttpServletRequest request) {
        String oaid = loginVo.getOaid();
        if(StrUtil.isEmpty(oaid)){
            return JsonResult.returnFail("当前手机类型不支持，请更换手机");
        }
        Users users = bizUserService.registerUserNew(loginVo, IpUtils.getIpAddr(request));
        redisService.set(users.getOpenid() + loginVo.getDeviceId(), users);
        UsersInfoVo usersInfoVo = getUsersInfoVo(users);
        return JsonResult.returnResult(JsonResult.SUCCESS, new JSONObject(usersInfoVo));
    }

    @PostMapping("registerOrLogin2.0")
    public JsonResult login116(LoginVo loginVo, HttpServletRequest request) {
        String oaid = loginVo.getOaid();
        if(StrUtil.isEmpty(oaid)){
            return JsonResult.returnFail("当前手机类型不支持，请更换手机");
        }
        Users users = bizUserService.registerUser(loginVo, IpUtils.getIpAddr(request));
        redisService.set(users.getOpenid() + users.getDeviceId(), users);
        UsersInfoVo usersInfoVo = getUsersInfoVo(users);
        return JsonResult.returnResult(JsonResult.SUCCESS, new JSONObject(usersInfoVo));
    }

    @PostMapping("info")
    public JsonResult getInfo(HttpServletRequest request, UserDailyActivityVo userDailyActivityVo) throws Exception {
        Users users = getUser(request);
        if (ObjectUtil.isNull(users)) {
            return JsonResult.returnResetLogin("登录失效、请重新登录");
        }
        users = bizUserService.selectById(users.getId());
        bizAntiCheatService.gatherAntiCheat(users, userDailyActivityVo, IpUtils.getIpAddr(request));
        //更新用户登录时间和IP
        iUserDailyActivityService.saveUserDaily(users, IpUtils.getIpAddr(request), userDailyActivityVo);
        redisService.set(users.getOpenid() + users.getDeviceId(), users);
        UsersInfoVo usersInfoVo = getUsersInfoVo(users);
        return JsonResult.returnResult(JsonResult.SUCCESS, new JSONObject(usersInfoVo));
    }

    @NotNull
    private UsersInfoVo getUsersInfoVo(Users users) {
        EntityWrapper<UsersLogout> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("ul_device_id", users.getDeviceId());
        entityWrapper.eq("ul_stats", 1);
        iUsersLogoutService.delete(entityWrapper);
        UsersInfoVo usersInfoVo = BeanUtil.toBean(users, UsersInfoVo.class);
        usersInfoVo.setLoginTime(DateUtil.format(new Date(), DateUtils.YYYY_MM_DD));
        usersInfoVo.setRisk_advertising_coins(iAntiCheatService.checkRiskAdvertisingCoins(users.getId()));
        usersInfoVo.setRisk_advertising_coins_than_equal(iAntiCheatService.checkRiskAdvertisingCoinsThanEqual(users.getId()));
        usersInfoVo.setRisk_advertising_coins_than_equal_two(iAntiCheatService.checkRiskAdvertisingCoinsThanEqualTwo(users.getId()));
        usersInfoVo.setRisk_white_list(iAntiCheatService.checkRiskWhiteList(users.getId()));
        return usersInfoVo;
    }

    @PostMapping("user_feedback")
    public JsonResult userFeedback(HttpServletRequest request) {
        Users users = getUser(request);
        String content = request.getParameter("content");
        boolean flag = bizUserService.userFeedback(users.getId(), content);
        if (flag) {
            return JsonResult.returnSuccess("提交成功");
        }
        return JsonResult.returnFail("服务器异常，请联系客服");
    }

    @PostMapping("count_friend")
    public JsonResult countFriend(HttpServletRequest request) {
        return JsonResult.returnResult(JsonResult.SUCCESS, bizUserService.countFriend(getUser(request).getId()));
    }

    @PostMapping("user_friend")
    public JsonResult listFriend(HttpServletRequest request) {
        Users users = getUser(request);
        PageVo pageVo = (PageVo) paramUtilsInterFase.getParam(request, PageVo.class);
        String effective = request.getParameter("status");
        return JsonResult.returnResult(JsonResult.SUCCESS, bizUserService.queryBizFriend(users.getId(), Integer.parseInt(effective), pageVo));
    }

    @PostMapping("afb_info")
    public JsonResult saveAfbInfo(HttpServletRequest request) {
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String uvChannel = request.getParameter("uvChannel");
        Users users = getUser(request);
        users.setAfbName(name);
        users.setAfbPhone(phone);
        try {
            boolean flag = bizUserService.saveAfbInfo(users,uvChannel);
            if (flag) {
                return JsonResult.returnSuccess("设置成功");
            } else {
                return JsonResult.returnFail("保存失败");
            }
        } catch (BizException e) {
            e.printStackTrace();
            return JsonResult.returnFail(e.getMessage());
        }
    }

    @PostMapping("to_day_statistics")
    public JsonResult statistics(HttpServletRequest request) {
        String oaid = request.getParameter("oaid");
        Users user = getUser(request);
        if (StrUtil.isEmpty(oaid)) {
            return JsonResult.returnResetLogin("登录失效，请重新登录");
        }
        if (!oaid.equals(user.getOaid())) {
            return JsonResult.returnResetLogin("操作异常，请重新登录");
        }
        return JsonResult.returnResult(JsonResult.SUCCESS, bizUserService.toDayStatistics(getUser(request).getId()));
    }

    @PostMapping("update_nickname")
    public JsonResult updateNickname(HttpServletRequest request) {
        Users users = getUser(request);
        users.setNickname(request.getParameter("nickname"));
        try {
            boolean flag = bizUserService.updateNickname(users);
            if (flag) {
                return JsonResult.returnSuccess("成功");
            } else {
                return JsonResult.returnFail("失败");
            }
        } catch (BizException e) {
            return JsonResult.returnFail(e.getMessage());
        }
    }


    @PostMapping("data_center")
    public JsonResult queryDataCenter(HttpServletRequest request) {
        Map<String, Object> map = bizUserService.queryTheCharts(getUser(request).getId());
        return JsonResult.returnResult(JsonResult.SUCCESS_3, map);
    }

    @PostMapping("the_charts")
    public JsonResult queryTheCharts(HttpServletRequest request) {
        String status = request.getParameter("status");
        List<BizRankingList> list = bizUserService.queryTheCharts(getUser(request).getId(), Integer.parseInt(status));
        return JsonResult.returnResult(JsonResult.SUCCESS, list);
    }

    @PostMapping("separation")
    public void queryTheAction(HttpServletRequest request) {
        String riskDoubleOpenBackstage = (String) redisService.get(RedisEnum.RISK_DOUBLE_OPEN_BACKSTAGE.getKey());
        if (RiskEnum.RISK_NO.getValue().equals(riskDoubleOpenBackstage)) {
            return;
        }
        String usId = request.getParameter("info");
        if (StrUtil.isEmpty(usId)) {
            return;
        }
        lock.lock();
        try {
            Users users = getUser(request);
            if (Integer.parseInt(usId) == users.getId()) {
                return;
            }
            AntiCheatDetail antiCheatDetail = new AntiCheatDetail();
            antiCheatDetail.setUsId(Integer.parseInt(usId));
            antiCheatDetail.setAcdDesc("双开");
            iUserDailyActivityService.saveStatus(antiCheatDetail, bizUserService.selectById(usId));
            iUserDailyActivityService.updateUserDailySeparation(Integer.parseInt(usId));

            AntiCheatDetail antiCheat = new AntiCheatDetail();
            antiCheat.setUsId(users.getId());
            antiCheat.setAcdDesc("双开");
            iUserDailyActivityService.saveStatus(antiCheat, users);
            iUserDailyActivityService.updateUserDailySeparation(users.getId());
        } finally {
            lock.unlock();
        }
    }

    /**
     * 注销用户
     *
     * @param request
     * @return
     */
    @PostMapping("logout")
    public JsonResult logout(HttpServletRequest request) {
        lock.lock();
        try {
            Users users = getUser(request);
            UsersLogout usersLogout = new UsersLogout();
            usersLogout.setUlId(users.getId());
            usersLogout.setUlDeviceId(users.getDeviceId());
            EntityWrapper<UsersLogout> entityWrapper = new EntityWrapper<>();
            entityWrapper.setEntity(usersLogout);
            int count = iUsersLogoutService.selectCount(entityWrapper);
            if (count <= 0) {
                iUsersLogoutService.insert(usersLogout);
            }
        } finally {
            lock.unlock();
        }
        return JsonResult.returnSuccess("申请成功");
    }
}
